from mini_tools.cjjtool import *
from sql import sqlseverDB
from . import MachineCodeGenerator
from . import config
import tkinter.messagebox  as messagebox
import time

machine_codes=config.machine_codes

class Register:
    def __init__(self):
        self.ms = sqlseverDB('{SQL Server}', '198.12.127.42,5810', 'auth', 'sa', 'Y3GwLHaP8zQ0seZG')
        self.machine_code = MachineCodeGenerator.MachineCodeGenerator().getMachineCode()

    # 校验
    def checkAuthored(self):
        global ms
        if machine_codes.get(self.machine_code):
            self.cjurlsq=1
            return True
        print("正在校验授权信息，请稍等...")
        try:
            
            ms=self.ms
            rs=ms.ExecQuery('select * from [user] where code=?',(self.machine_code,))
            print(f'授权列表:{rs}')
            
            if not rs:
                print("您的设备没有授权，暂无法使用！")
                return False
            else:
                cur_user=rs[0]
                self.cjurlsq=cur_user[-2]
                endTime = cur_user[3]
                if endTime == 0:
                    print("您的设备没有授权，暂无法使用！")
                    return False
                if endTime == -1:
                    print("您的设备已获得【永久】使用授权！")
                    return True
                if endTime > 0:
                    if time.time()-endTime>0:
                        print("设备授权时间过期,请重新申请" %dt)
                        return False
                    time_local = time.localtime(endTime)
                    dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
                    print("您的设备获得临时授权，授权有效期至【%s】" %dt)
                    return True
        except:
            print("网络请求超时，请稍后再试！")
            return False

def authmain():
    global ms
    register = Register()

    if (not register.checkAuthored()):
        if messagebox.askquestion('提示','是否申请授权?'):

            ipnumber=input("请输入手机号码:").strip()
            if len(ipnumber)!=11 or not ipnumber.isdigit():
                print('请输入正确的号码:')
                return
            rs= ms.ExecQuery('select count(*) from apply where code=?',(register.machine_code,))
            if rs[0][0]:
                aff=ms.ExecNoQuery('update apply set status=0 where code=?',(register.machine_code,))
                if aff:
                    print(f'机器码:{register.machine_code},成功申请 \n请联系 17805973185 获取使用授权，授权后即可正常使用')
                    messagebox.showinfo('提示',f'机器码:{register.machine_code},成功申请\n请联系 17805973185 获取使用授权，授权后即可正常使用')
                return False
        
            aff=ms.ExecNoQuery('insert into apply([code],[phone_number],[apply_time]) values(?,?,?)',(register.machine_code,ipnumber,int(time.time())))
            if aff:
                print(f'机器码:{register.machine_code},成功申请 \n请联系 17805973185 获取使用授权，授权后即可正常使用')
                messagebox.showinfo('提示',f'机器码:{register.machine_code},成功申请\n请联系 17805973185 获取使用授权，授权后即可正常使用')
        
        return False
    else:
        return (True,register.cjurlsq)



